package ca.ualberta.cs.CLRDB.conference;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import ca.ualberta.cs.CLRDB.DatabaseController;
import ca.ualberta.cs.CLRDB.interfaces.EntityRelManagement;
import ca.ualberta.cs.DB2ExceptionHandling.DB2SqlException;

public class ConferenceController extends EntityRelManagement{
	
	static RolesManagement rolesMgmt = new RolesManagement();
	static PaperAssignments assignmentsMgmt = new PaperAssignments();
	static PhaseManagement phaseMgmt = new PhaseManagement(); 
	
	public void initialize(){
		try{
			Connection con = DatabaseController.connectToDB();
			if( con == null ) {//in case of exception
		   		System.out.println("Failed to connect to DB, none of DB queries will be handled from now. Try again.");
//		   		return false;
		   		return;
		   	}
			Statement statement = con.createStatement();
//			boolean ret = 
				initialize(statement);
			statement.close();
			con.commit();
			con.close();
//			return ret;
		}
		catch(SQLException e){
			DB2SqlException.printSqlErrorMsg(e);
//			return false;
		}		
	}

	public void initialize(Statement statement){
		
		try{
			if(!testCLRDBtablesExist(statement)){
				System.out.println("You should first create the base database.");
//				return false;
				return;
			}
			rolesMgmt.initialize(statement);
			phaseMgmt.initialize(statement);
			assignmentsMgmt.initialize(statement);
			
		}catch(SQLException e){
			DB2SqlException.printSqlErrorMsg(e);
//			return false;
		}
//		return true;
	}

	private boolean testCLRDBtablesExist(Statement statement){
		try {
			ResultSet res = statement.executeQuery("SELECT COUNT(*) AS NUM FROM " +
					"SYSCAT.TABLES WHERE SYSCAT.TABLES.TABNAME = 'ANNOTATION'");
			if(res.next()){
				int num = res.getInt("NUM");
				if(num > 0)
					return true;
			}
		} catch (SQLException e) {
			DB2SqlException.printSqlErrorMsg(e);
		}
		return false;
	}

}
